package com.qianfeng.admin.shiro;


import com.qianfeng.entity.dto.Admin;
import com.qianfeng.entity.po.LoginAdmin;
import com.qianfeng.http.ResultCode;
import com.qianfeng.service.impl.AdminService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

public class CustomRealm extends AuthorizingRealm {
    @Autowired
    private AdminService adminService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return new SimpleAuthorizationInfo();
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        String password = new String(token.getPassword());
        Admin admin = adminService.getByUsername(username);
        if (admin == null){
            throw new RuntimeException(ResultCode.LOGIN_ERROR.getDescription());
        }
        if (! admin.getPassword().equals(password)){
            throw new RuntimeException(ResultCode.LOGIN_ERROR.getDescription());
        }
        LoginAdmin loginAdmin = new LoginAdmin();
        BeanUtils.copyProperties(admin, loginAdmin);
        return new SimpleAuthenticationInfo(loginAdmin , admin.getPassword() , admin.getUsername());
    }
}
